package com.hephesto.infra.security.crypto.engines;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import com.hephesto.infra.security.crypto.ICryptographer;
import com.hephesto.infra.security.crypto.model.CryptographerException;

/**
 * @author rocha
 *
 */
public class CryptographerBehaviorAES implements ICryptographer {
	
	/*
	 *  
	 */
	private Cipher cipher;

	/**
	 * 
	 */
	private SecretKeySpec kspec;

	/**
	 * 
	 */
	public CryptographerBehaviorAES(String key) throws CryptographerException {
		try {
			byte[] raw = key.getBytes();
			kspec = new SecretKeySpec(raw, "AES");
			cipher = Cipher.getInstance("AES");
		} catch (NoSuchAlgorithmException e) {
			throw new CryptographerException(e.getMessage());
		} catch (NoSuchPaddingException e) {
			throw new CryptographerException(e.getMessage());
		}
	}
	
	/**
	 * @see com.hephesto.infra.security.crypto.ICryptographerSimetric#encrypt(byte[])
	 */
	@Override
	public byte[] encrypt(byte[] bytes) throws CryptographerException {
		try {
			this.cipher.init(Cipher.ENCRYPT_MODE, kspec);
			return this.cipher.doFinal( bytes );
		} catch (InvalidKeyException e) {
			throw new CryptographerException(e.getMessage());
		} catch (IllegalBlockSizeException e) {
			throw new CryptographerException(e.getMessage());
		} catch (BadPaddingException e) {
			throw new CryptographerException(e.getMessage());
		}
	}

	/**
	 * @see com.hephesto.infra.security.crypto.ICryptographerSimetric#decrypt(byte[])
	 */
	@Override
	public byte[] decrypt(byte[] bytes) throws CryptographerException {
		try {
			this.cipher.init(Cipher.DECRYPT_MODE, kspec);
			return this.cipher.doFinal( bytes );
		} catch (InvalidKeyException e) {
			throw new CryptographerException(e.getMessage());
		} catch (IllegalBlockSizeException e) {
			throw new CryptographerException(e.getMessage());
		} catch (BadPaddingException e) {
			throw new CryptographerException(e.getMessage());
		}
	}
	
}